package com.leha.mp.core.services.imp;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.leha.mp.core.Utils.BizTransferHelper;
import com.leha.mp.core.Utils.Page;
import com.leha.mp.core.Utils.RTCHelper;
import com.leha.mp.core.constants.BizConstants;
import com.leha.mp.core.constants.CoreErrorDict;
import com.leha.mp.core.dao.*;
import com.leha.mp.core.entity.mybatis.*;
import com.leha.mp.core.entity.templateMsg.ConsultingCancleMsg;
import com.leha.mp.core.entity.templateMsg.ConsultingEvaluateRemindMsg;
import com.leha.mp.core.entity.templateMsg.MsgConsultingReplayedMsg;
import com.leha.mp.core.entity.templateMsg.OrderStatusMsg;
import com.leha.mp.core.entity.vo.*;
import com.leha.mp.core.services.*;
import com.leha.utils.DateTool;
import com.tencent.qcloud.roomservice.webrtc.pojo.Request.CreateRoomReq;
import com.tencent.qcloud.roomservice.webrtc.pojo.Request.EnterRoomReq;
import com.tencent.qcloud.roomservice.webrtc.pojo.Request.GetRoomListReq;
import com.tencent.qcloud.roomservice.webrtc.pojo.Request.QuitRoomReq;
import com.tencent.qcloud.roomservice.webrtc.pojo.Response.CreateRoomRsp;
import com.tencent.qcloud.roomservice.webrtc.pojo.Response.EnterRoomRsp;
import com.tencent.qcloud.roomservice.webrtc.pojo.Response.GetLoginInfoRsp;
import com.tencent.qcloud.roomservice.webrtc.pojo.Response.GetRoomListRsp;
import com.tencent.qcloud.roomservice.webrtc.pojo.WebRTCRoom;
import com.tencent.qcloud.roomservice.webrtc.service.WebRTCRoomService;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Log4j2
public class ConfluenceServicesImpl implements ConfluenceServices {
    @Autowired
    PlProductMapper productMapper;
    @Autowired
    PlConsultingMapper consultingMapper;
    @Autowired
    PlUserVipMapper userVipMapper;
    @Autowired
    PlUserMapper userMapper;
    @Autowired
    QaDoctorMapper doctorMapper;
    @Autowired
    HidingCallServices hidingCallServices;
    @Autowired
    PlMediaRecordMapper recordMapper;
    @Autowired
    PlDoctorCommentMapper commentMapper;
    @Autowired
    PlDoctorLabelMapper labelMapper;
    @Autowired
    PlLabelMapper dcLabelMapper;
    @Autowired
    WebRTCRoomService rtcRoomService;
    @Autowired
    ErrorMessageServices errorMessageServices;
    @Autowired
    PlConsultingMsgMapper msgMapper;
    @Autowired
    PushServices pushServices;
    @Autowired
    AppDoctorServices doctorServices;
    @Autowired
    PlVipMapper vipMapper;
    @Autowired
    AppUserService userService;
    @Autowired
    BedgeServices bedgeServices;
    @Autowired
    BalanceServices balanceServices;
    @Autowired
    PlOrderMapper orderMapper;
    @Autowired
    PlCaseMapper caseMapper;


    private String phoneCallback = ResourceBundle.getBundle("config").getString("call.cb");

    private static final Logger LOG = LoggerFactory.getLogger(ConfluenceServicesImpl.class);
    @Override
    public Boolean userPaySuccess(PlOrder order) {
        PlProduct pr = productMapper.selectByPrimaryKey(order.getProductId());
        log.info("用户支付成功，进入业务处理，商品编号："+pr.getType().toString());
        if(isConsulting(pr.getType())) {
            log.info("咨询类业务："+order.getOrderId());
            PlConsultingExample ex = new PlConsultingExample();
            ex.createCriteria().andOrderIdEqualTo(order.getOrderId());
            List<PlConsulting> consultings = consultingMapper.selectByExample(ex);
            if(consultings.size()!=1) {
                return false;
            }
            PlConsulting consulting = consultings.get(0);
            consulting.setStatus(BizConstants.Consulting_Status_Payed);
            consulting.setMaxTime(pr.getTime());
            consultingMapper.updateByPrimaryKeySelective(consulting);
            //todo 通知医生有患者付费咨询
            PushVo vo = new PushVo("user_payed", consulting);
            pushServices.SendMessageToDoctor(consulting.getDoctorId(), JSON.toJSONString(consulting));

            OrderStatusMsg msg = OrderStatusMsg.msgBuilder(order.getOrderNo(), consulting.getConsultingType(), consulting.getConsultingType()==1?"待回复":"待确认");
            pushServices.SendMessageToUserWithMp(consulting.getUserId(), JSON.toJSONString(msg));
            doctorServices.updateDoctorStatics(pr.getDoctorId());
            if(consulting.getConsultingId() == BizConstants.Consulting_Type_Msg) {
                bedgeServices.UpdateDoctorBedge(pr.getDoctorId(), BedgeServices.Type_Doctor_My_Msg, consulting.getConsultingId(), 1);
            } else if(consulting.getConsultingId() == BizConstants.Consulting_Type_Phone) {
                bedgeServices.UpdateDoctorBedge(pr.getDoctorId(), BedgeServices.Type_Doctor_My_Phone, consulting.getConsultingId(), 1);
            } else if(consulting.getConsultingId() == BizConstants.Consulting_Type_Video) {
                bedgeServices.UpdateDoctorBedge(pr.getDoctorId(), BedgeServices.Type_Doctor_My_Video, consulting.getConsultingId(), 1);
            }
        } else {
            log.info("VIP类业务："+order.getOrderId());
            genVipRecord(order.getUid(), order.getOrderId(), pr);
        }
        return true;
    }


    public boolean isConsulting(Integer type) {
        if(type==BizConstants.Product_Type_Msg ||
                type==BizConstants.Product_Type_Phone ||
                type==BizConstants.Consulting_Type_Video) {
            return true;
        }
        return false;
    }

    @Override
    public PlConsulting genConsulting(Integer uid, Integer orderId, PlProduct product, String extraData, Boolean isVip) {
        PlConsulting consulting = new PlConsulting();
        consulting.setMaxTime(product.getTime());
        consulting.setStatus(BizConstants.Consulting_Status_Paying);
        consulting.setConsultingType(product.getType().byteValue());
        consulting.setUserId(uid);
        consulting.setOrderId(orderId);
        consulting.setDoctorId(product.getDoctorId());
        consulting.setExtraData(extraData);
        if(isVip) {
            consulting.setStatus(BizConstants.Consulting_Status_Payed);
        }
        try {
            if(product.getType().byteValue() != BizConstants.Consulting_Type_Msg) {
                JSONObject obj = JSON.parseObject(extraData);
                consulting.setBeginTime(DateTool.strToDate(obj.getString("day") + " " + obj.getString("timeStr"), "yyyy-MM-dd HH:mm"));
                if (consulting.getBeginTime().getTime() <= new Date().getTime()) {
                    return null;
                }
            }
        } catch (Exception e) {
            LOG.error("Json解析错误，" + extraData);
        }
        consultingMapper.insertSelective(consulting);
        return consulting;
    }

    @Override
    public boolean beginPhoneServ(Integer consultingId) {
        PlConsulting consulting = consultingMapper.selectByPrimaryKey(consultingId);
        PlUser u = userMapper.selectByPrimaryKey(consulting.getUserId());
        QaDoctor doctor = doctorMapper.selectByPrimaryKey(consulting.getDoctorId());
        HashMap<String, Object> ret = hidingCallServices.MakeDoubleSideCall(doctor.getPhone(), u.getPhone(),consulting.getMaxTime()*60,  phoneCallback, consultingId.toString());
        log.info("make call ret:", JSONObject.toJSONString(ret));
        insertMediaRecord((String) ret.get("callSid"), consultingId, doctor.getId(), u.getUid(), BizConstants.Consulting_Type_Phone);
        consulting.setStatus(BizConstants.Consulting_Status_Serving);
        consultingMapper.updateByPrimaryKeySelective(consulting);
        return true;
    }

    @Override
    public void endPhone(HashMap<String, String> ret) {
        log.info("EndPhone data:", JSONObject.toJSONString(ret));
        String callSid = ret.get("callSid");
        PlMediaRecord record = recordMapper.selectByPrimaryKey(callSid);
        record.setFulldata(JSONObject.toJSONString(ret));
        record.setEndTime(DateTool.strToDate(ret.get("endtime"), "yyyyMMddHHmmss"));
        recordMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public boolean Evaluate(Integer consultingId, Integer star, String impress, String content, Boolean isAnonymous) {
        PlConsulting pc = consultingMapper.selectByPrimaryKey(consultingId);
        if(pc.getStatus() == BizConstants.Consulting_Status_Finished) {
            PlDoctorComment comment = new PlDoctorComment();
            comment.setContent(content);
            comment.setDoctorId(pc.getDoctorId());
            comment.setUserId(pc.getUserId());
            comment.setEmpress(star);
            comment.setIsanonymous((byte) (isAnonymous?1:0));
            comment.setConsultingId(consultingId);
            comment.setLabel(impress);
            commentMapper.insertSelective(comment);

            String[] labes = impress.split(",");
            PlDoctorLabel l = new PlDoctorLabel();
            l.setDoctorId(pc.getDoctorId());
            l.setCount(1);
            for(String label: labes) {
                l.setContent(label);
                labelMapper.insertSelective(l);
            }
            pc.setStatus(BizConstants.Consulting_Status_Closed);
            consultingMapper.updateByPrimaryKeySelective(pc);
            return true;
        }
        return false;
    }

    @Override
    public List<PlLabel> getEvaluateLabel() {
        return dcLabelMapper.selectByExample(new PlLabelExample());
    }

    //生成有效的房间号，如果第一次则创建房间，如果已经有房间则找出可用房间
    private String genRoomId(PlConsulting consulting, Boolean isDoctor) {
        PlMediaRecordExample ex = new PlMediaRecordExample();
        ex.createCriteria().andConsultingIdEqualTo(consulting.getConsultingId());
        ex.setOrderByClause("begin_time desc");
        List<PlMediaRecord> res = recordMapper.selectByExample(ex);
        if(res.size()!=0) {
            String roomId = res.get(0).getRefId();
            WebRTCRoom room =  rtcRoomService.getRoomById(roomId);
            if(room!=null) {
                return room.getRoomID();
            }
        }
        CreateRoomReq req = new CreateRoomReq();
        req.setRoomInfo("1对1咨询房间");
        if(isDoctor) {
            req.setUserID(RTCHelper.DocterUidGen(consulting.getDoctorId()));
            req.setNickName("医生");
        } else {
            req.setUserID(RTCHelper.UserUidGen(consulting.getUserId()));
            req.setNickName("患者");
        }
        CreateRoomRsp resp = rtcRoomService.createRoom(req);
        insertMediaRecord(resp.getRoomID(), consulting.getConsultingId(), consulting.getDoctorId(), consulting.getUserId(), BizConstants.Consulting_Type_Video);
        return resp.getRoomID();
    }

    @Override
    public VideoSrvVo beginVideoServ(Integer consultingId) {
        PlConsulting consulting = consultingMapper.selectByPrimaryKey(consultingId);
        GetLoginInfoRsp loginRsp = rtcRoomService.getLoginInfo(RTCHelper.DocterUidGen(consulting.getDoctorId()));

        String roomId = genRoomId(consulting, true);

        EnterRoomReq enterReq = new EnterRoomReq();
        enterReq.setUserID(RTCHelper.DocterUidGen(consulting.getDoctorId()));
        enterReq.setNickName("医生");
        enterReq.setRoomID(roomId);
        EnterRoomRsp enterResp = rtcRoomService.enterRoom(enterReq);

        VideoSrvVo vo = new VideoSrvVo();
        vo.setEnterRoomInfo(enterResp);
        vo.setLoginInfo(loginRsp);

        consulting.setStatus(BizConstants.Consulting_Status_Serving);
        consultingMapper.updateByPrimaryKeySelective(consulting);

        return vo;
    }

    @Override
    public GetRoomListRsp getRoomList(Integer uid) {
        PlMediaRecordExample ex = new PlMediaRecordExample();
        ex.createCriteria().andUserIdEqualTo(uid).andEndTimeIsNull().andTypeEqualTo(BizConstants.Consulting_Type_Video);
        List<PlMediaRecord> res = recordMapper.selectByExample(ex);

        GetRoomListReq req = new GetRoomListReq();
        req.setIndex(0);
        req.setCount(10000);
        GetRoomListRsp resp = rtcRoomService.getRoomList(req);

        Set<String> set = new HashSet<>();
        for(PlMediaRecord ss: res) {
            set.add(ss.getRefId());
        }
        ArrayList<WebRTCRoom> rooms = resp.getRooms();
        ArrayList<WebRTCRoom> filterRooms = new ArrayList<>();
        for(WebRTCRoom r:rooms) {
            if(set.contains(r.getRoomID())) {
                filterRooms.add(r);
            }
        }
        resp.setRooms(filterRooms);
        return resp;
    }

    @Override
    public VideoSrvVo userEnterRtcRoom(Integer consultingId) {
        PlConsulting consulting = consultingMapper.selectByPrimaryKey(consultingId);
        GetLoginInfoRsp loginRsp = rtcRoomService.getLoginInfo(RTCHelper.UserUidGen(consulting.getUserId()));
        String roomId = genRoomId(consulting, false);

        EnterRoomReq enterReq = new EnterRoomReq();
        enterReq.setUserID(RTCHelper.UserUidGen(consulting.getUserId()));
        enterReq.setNickName("患者");
        enterReq.setRoomID(roomId);
        EnterRoomRsp enterResp = rtcRoomService.enterRoom(enterReq);

        VideoSrvVo vo = new VideoSrvVo();
        vo.setEnterRoomInfo(enterResp);
        vo.setLoginInfo(loginRsp);
        return vo;
    }

    @Override
    public Boolean endVideo(Integer did, Integer consultingId, String roomId) {
        PlMediaRecordExample ex = new PlMediaRecordExample();
        ex.createCriteria().andDoctorIdEqualTo(did).andRefIdEqualTo(roomId);
        List<PlMediaRecord> res = recordMapper.selectByExample(ex);
        PlMediaRecord rr = new PlMediaRecord();
        rr.setEndTime(new Date());
        recordMapper.updateByPrimaryKeySelective(rr);

        QuitRoomReq req = new QuitRoomReq();
        req.setRoomID(roomId);
        req.setUserID(RTCHelper.DocterUidGen(did));
        rtcRoomService.quitRoom(req);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveMsg(PlConsultingMsg plConsultingMsg) {
        PlConsulting consulting = consultingMapper.selectByPrimaryKey(plConsultingMsg.getConsultingId());
        Integer timesleft = consulting.getMaxTime();
        if(plConsultingMsg.getIsReplay().equals(BizConstants.MsgFromUser) &&
                consulting.getStatus()>=BizConstants.Consulting_Status_Finished){
            if(timesleft <= 0) {
                return -1;
            }
            consulting.setMaxTime(timesleft-1);
            consultingMapper.updateByPrimaryKeySelective(consulting);
        } else if(plConsultingMsg.getIsReplay().equals(BizConstants.MsgFromDoctor)) {
            consulting.setStatus(BizConstants.Consulting_Status_Serving);
            consultingMapper.updateByPrimaryKeySelective(consulting);
        }

        int ret = msgMapper.insertSelective(plConsultingMsg);
        PushVo vo = new PushVo("msg_push", plConsultingMsg);
        if(ret>0) {
            if(plConsultingMsg.getIsReplay().equals(0)) {
                pushServices.SendMessageToDoctor(plConsultingMsg.getDoctorId(), JSON.toJSONString(vo));
                bedgeServices.UpdateDoctorBedge(plConsultingMsg.getDoctorId(), BedgeServices.Type_Doctor_My_Msg, plConsultingMsg.getConsultingId(), 1);
            } else {
                pushServices.SendMessageToUser(plConsultingMsg.getUserId(), JSON.toJSONString(vo));
                DoctorBaseInfoVo v = doctorServices.getDoctorBaseInfo(plConsultingMsg.getDoctorId());
                MsgConsultingReplayedMsg msg = MsgConsultingReplayedMsg.msgBuilder(
                        BizTransferHelper.ConsultingDecode(consulting.getExtraData(), "describe", "请进入小程序查看详情"),
                        plConsultingMsg.getMsgType()==BizConstants.MsgConsulting_MsgType_Text ? plConsultingMsg.getMsgContent():"多媒体信息，请进入普乐云康小程序查看",
                        v.getName());
                //pushServices.SendMessageToUserWithMp(plConsultingMsg.getUserId(), "您收到的新的回复");
                bedgeServices.UpdateUserBedge(plConsultingMsg.getUserId(), BedgeServices.Type_User_My_Msg, plConsultingMsg.getConsultingId(), 1);
            }
            return timesleft-1;
        }
        return -1;
    }

    @Override
    public MsgConsultingVo getConsultingMsg(Integer consultingId, Page page) {
        MsgConsultingVo vv = new MsgConsultingVo();

        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        PlConsultingMsgExample ex = new PlConsultingMsgExample();
        ex.createCriteria().andConsultingIdEqualTo(consultingId);
        ex.setOrderByClause("create_time asc");
        vv.setMsgs(msgMapper.selectByExample(ex));

        vv.setCanExtend(true);
        vv.setConsulting(consultingMapper.selectByPrimaryKey(consultingId));
        return vv;
    }

    @Override
    public List<ConsultingInfoVO> getUserConsulting(Integer uid, Page page, Integer type, String status) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        PlConsultingExample ex = new PlConsultingExample();
        PlConsultingExample.Criteria cr = ex.createCriteria().andUserIdEqualTo(uid);
        if(type==null) {
            type = 0;
        }
        if(type>=1 && type<=3) {
            cr.andConsultingTypeEqualTo(type.byteValue());
        } else if(type==4) {
            cr.andConsultingTypeBetween(BizConstants.Consulting_Type_Phone, BizConstants.Consulting_Type_Video);
        }
        if(status!=null && !status.isEmpty()) {
            String[] types = status.split(",");
            List<Byte> st = new ArrayList<>();
            for(String t:types) {
                st.add(Byte.valueOf(t));
            }
            cr.andStatusIn(st);
        }
        ex.setOrderByClause("create_time desc");
        List<PlConsulting> consultings = consultingMapper.selectByExample(ex);
        List<DoctorBaseInfoVo> doctorBaseInfoVos = userService.getMyDoctor(uid);
        List<ConsultingInfoVO> rets = new ArrayList<>();
        for(PlConsulting consulting: consultings) {
            ConsultingInfoVO v = new ConsultingInfoVO();
            v.setData(consulting);
            for(DoctorBaseInfoVo base:doctorBaseInfoVos) {
                if(base.getId().equals(consulting.getDoctorId())) {
                    v.setDoctorInfo(base);
                    break;
                }
            }
            rets.add(v);
        }
        return rets;
    }

    @Override
    public boolean recallPhone(Integer consultingId) {
        PlConsulting consulting = consultingMapper.selectByPrimaryKey(consultingId);
        if(consulting.getStatus()>= BizConstants.Consulting_Status_Finished) {
            return false;
        }
        PlUser u = userMapper.selectByPrimaryKey(consulting.getUserId());
        QaDoctor doctor = doctorMapper.selectByPrimaryKey(consulting.getDoctorId());
        HashMap<String, Object> ret = hidingCallServices.MakeDoubleSideCall(doctor.getPhone(), u.getPhone(),consulting.getMaxTime()*60,  phoneCallback, consultingId.toString());
        insertMediaRecord((String) ret.get("callSid"), consultingId, doctor.getId(), u.getUid(), BizConstants.Consulting_Type_Phone);
        return true;
    }

    @Override
    public Boolean doctorFinishConsulting(Integer doctorId, Integer consultingId, String report) {
        PlConsulting consulting = consultingMapper.selectByPrimaryKey(consultingId);
        if(!consulting.getDoctorId().equals(doctorId)) {
            errorMessageServices.setError(CoreErrorDict.InvalideDoctorId);
            return false;
        }
        consulting.setEndTime(new Date());
        consulting.setMedicalReport(report);
        consulting.setStatus(BizConstants.Consulting_Status_Finished);
        //pushServices.SendMessageToUserWithMp(consulting.getUserId(), "您的咨询已完成，您的评价是给医生最好的感谢和鞭策！");
        PlUser ui = userMapper.selectByPrimaryKey(consulting.getUserId());
        DoctorBaseInfoVo di = doctorServices.getDoctorBaseInfo(consulting.getDoctorId());
        ConsultingEvaluateRemindMsg msg = ConsultingEvaluateRemindMsg.msgBuilder(
                String.format("%s %s %s岁",ui.getName(), ui.getSex()==1?"男":"女", ui.getAge()),
                String.format("%s %s %s", di.getHospital(), di.getName(), di.getTitle())
        );
        pushServices.SendMessageToUserWithMp(ui.getUnionid(), JSON.toJSONString(msg));

        bedgeServices.UpdateUserBedge(consulting.getUserId(), BedgeServices.Type_User_My_Evaluate, consultingId, 1);
        if(consulting.getOrderId() != 0) {
            addDoctorBill(consulting);
        }
        return consultingMapper.updateByPrimaryKeySelective(consulting) > 0;
    }

    private void addDoctorBill(PlConsulting consulting) {
        PlDoctorBill bill = new PlDoctorBill();
        bill.setRefId(consulting.getConsultingId());
        bill.setDoctorId(consulting.getDoctorId());
        bill.setActiveTime(DateTool.DayOp(new Date(), 7));
        bill.setDes(getConsultingDes(consulting.getConsultingType()));
        bill.setType(consulting.getConsultingType().intValue());
        PlOrder order = orderMapper.selectByPrimaryKey(consulting.getOrderId());
        bill.setIncome(order.getOrderFee().doubleValue()/100.0);
        balanceServices.AddBill(bill);
    }

    private String getConsultingDes(Byte consultingType) {
        switch (consultingType) {
            case BizConstants.Consulting_Type_Msg:
                return "图文咨询";
            case BizConstants.Consulting_Type_Phone:
                return "电话咨询";
            case BizConstants.Consulting_Type_Video:
                return "视频咨询";
        }
        return "";
    }

    @Override
    public boolean canCancel(Byte status) {
        if(status.equals(BizConstants.Consulting_Status_Payed) ||
                status.equals(BizConstants.Consulting_Status_RefundDoubleCheck) ||
                status.equals(BizConstants.Consulting_Status_Accepted) ||
                status.equals(BizConstants.Consulting_Status_AutoClose) ||
                status.equals(BizConstants.Consulting_Status_Reject)) {
            return true;
        }
        return false;
    }

    @Override
    public ConsultingInfoVO getConsultingbyId(Integer consultingId) {
        ConsultingInfoVO vo = new ConsultingInfoVO();
        vo.setData(consultingMapper.selectByPrimaryKey(consultingId));
        vo.setDoctorInfo(doctorServices.getDoctorBaseInfo(vo.getData().getDoctorId()));
        vo.setUserInfo(userMapper.selectByPrimaryKey(vo.getData().getUserId()));
        if(vo.getData().getConsultingType()!=BizConstants.Consulting_Type_Msg){
            PlMediaRecordExample ex = new PlMediaRecordExample();
            ex.createCriteria().andConsultingIdEqualTo(consultingId);
            List<PlMediaRecord> res = recordMapper.selectByExample(ex);
            vo.setRecord(res);
        }
        if(vo.getData().getStatus()==BizConstants.Consulting_Status_Closed) {
            PlDoctorCommentExample ex = new PlDoctorCommentExample();
            ex.createCriteria().andConsultingIdEqualTo(consultingId);
            List<PlDoctorComment> res = commentMapper.selectByExample(ex);
            if(res.size()>0) {
                vo.setComment(res.get(0));
            }
        }
        return vo;
    }

    @Override
    public void updateVip(Integer uid, Integer doctorId, Integer pid) {
        PlProduct pr = productMapper.selectByPrimaryKey(pid);
        PlUserVipKey key = new PlUserVipKey();
        key.setUserId(uid);
        key.setDoctorId(doctorId);
        PlUserVip uv = userVipMapper.selectByPrimaryKey(key);
        if(uv == null) {
            PlUserVip uvip = new PlUserVip();
            uvip.setDoctorId(pr.getDoctorId());
            uvip.setUserId(uid);
            uvip.setExpiredTime(DateTool.DayOp(new Date(), pr.getTime()));
            uvip.setMsgTimesLeft(50);
            uvip.setPhoneTimesLeft(2);
            uvip.setVideoTimesLeft(2);
            userVipMapper.insertSelective(uvip);
        } else {
            Date beginTime = new Date();
            beginTime = beginTime.getTime() > uv.getExpiredTime().getTime() ? beginTime : uv.getExpiredTime();
            uv.setExpiredTime(DateTool.DayOp(beginTime, pr.getTime()));
            uv.setMsgTimesLeft(uv.getMsgTimesLeft()+50);
            uv.setPhoneTimesLeft(uv.getPhoneTimesLeft()+2);
            uv.setVideoTimesLeft(uv.getVideoTimesLeft()+2);
            userVipMapper.updateByPrimaryKeySelective(uv);
        }
    }

    @Override
    public void updateDoctorStatics(Integer doctorId) {

    }

    @Override
    public boolean genVipRecord(Integer uid, Integer orderId, PlProduct product) {
        PlVip record = new PlVip();
        record.setDoctorId(product.getDoctorId());
        record.setUserId(uid);
        record.setOrderId(orderId);
        record.setVipTime(product.getTime());
        record.setProductId(product.getProductId());
        vipMapper.insertSelective(record);
        //逻辑修改，医生默认直接通过Vip请求
        doctorServices.acceptVipRequest(product.getDoctorId(), record.getVipId(), BizConstants.Op_Accept);
        return true;
    }

    private boolean insertMediaRecord(String refid, Integer consultingId, Integer did, Integer uid, Byte consultingType) {
        PlMediaRecord record = new PlMediaRecord();
        record.setBeginTime(new Date());
        record.setConsultingId(consultingId);
        record.setDoctorId(did);
        record.setUserId(uid);
        record.setRefId(refid);
        record.setType(consultingType);
        return recordMapper.insertSelective(record) > 0;
    }
}
